package org.smart4j.framework.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by Wangminze on 2016/12/17.
 * Description: 反射工具类
 */
public final class ReflectionUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

    public static Object newInstance(Class<?> cls) {
        Object instance;
        try {
            instance = cls.newInstance();
        } catch (Exception e) {
            LOGGER.error("New instance failure.", e);
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * author: Wangminze
     * date: 2016/12/31
     * description:  根据类名获取实例对象
     * @param className 类名称，包名+类名
     * @return
     */
    public static Object newInstance(String className) {
        Object instance;
        try {
            Class cls = Class.forName(className);
            instance = cls.newInstance();
        } catch (Exception e) {
            LOGGER.error("New instance failure.", e);
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     * author: Wangminze
     * date: 2016/12/17
     * description:调用方法
     *
     * @param obj
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object obj, Method method, Object... args) {
        Object result;
        try {
            method.setAccessible(true);
            result = method.invoke(obj, args);
        } catch (Exception e) {
            LOGGER.error("Invoke method failure", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    public static void setField(Object obj, Field field, Object value) {
        try {
            field.setAccessible(true);
            field.set(obj, value);
        } catch (Exception e) {
            LOGGER.error("Set field failure", e);
            throw new RuntimeException(e);
        }
    }
}
